package com.zy.design.pattern.strategy;

import com.zy.design.pattern.strategy.sort.ISort;
import com.zy.design.pattern.strategy.sort.SortFactory;
import org.apache.commons.compress.utils.Lists;

import java.io.File;
import java.util.List;

/**
 * @author zhaoyi
 * @date 2021/8/17 17:10
 * 主类
 */
public class Sorter {

    private static final List<Rule> ruleList = Lists.newArrayList();
    private static final long GB = 1000 * 1024 * 1024;

    //加载规则 spring 的话可以通过 @Autowired 来自动注入
    static {
        ruleList.add(new Rule(0, 6 * GB, SortFactory.getSort("LocalSort")));
        ruleList.add(new Rule(6 * GB, 10 * GB, SortFactory.getSort("ExternalSort")));
        ruleList.add(new Rule(10 * GB, Long.MAX_VALUE, SortFactory.getSort("ConcurrentExternalSor")));
    }

    public void sortFile(String filePath) {
        File file = new File(filePath);
        long length = file.length();
        ISort sort = null;
        for (Rule rule : ruleList) {
            boolean match = rule.match(length);
            if (match) {
                sort = rule.getSort();
                break;
            }
        }
        if (sort == null) {
            throw new RuntimeException("无对应排序实现: " + length);
        }
        sort.sort(filePath);
    }


}
